<template>
  <cml-module :moduleName="$t('cmlpanel.remote')"
    icon="remote"
    v-bind="$attrs">
    <remote v-if="$_auth.includes('remote')"
      :isOpen="isOpen"
      :loading="loading"
      @change="changeConnect($event, true)" />

    <qr-image v-if="$_auth.includes('remote') && isOpen"
      :failed="failed"
      :code="code"
      @regen="regen"></qr-image>
  </cml-module>
</template>
<script>
import CmlModule from '../cml-module'
import Remote from './connect'
import './qr-image.js'
import { connectWebsocket } from '@/assets/js/app/utils/sys-utils/ws_manager'
const projectId = require('../../../../../../../package.json').projectId
export default {
  name: 'RemoteControl',
  components: {
    CmlModule,
    Remote
  },
  model: {},
  props: {},
  data() {
    return {
      code: '',
      failed: false,
      isOpen: false,
      loading: false
    }
  },
  computed: {},
  watch: {
    '$store.state.env.customer.info.code': {
      handler: function (newVal, oldVal) {
        if (newVal === oldVal) return
        const { code } = this.$store.state.env.customer.info
        if (code) {
          this.connectToWSServer(code)
        }
      },
      deep: true
    }
  },
  created() {
    app.adminServer.ws?.addEventListener('open', () => {
      // console.log(this.$store.state.env.customer.info.code)
      // console.log(this.$store.state.env)
      this.code = this.$store.state.env.customer.info.code
      this.isOpen = true
    })
    app.adminServer.ws?.addEventListener('close', () => {
      this.code = ''
      this.isOpen = false
    })
  },
  mounted() {},
  beforeDestroy() {},
  methods: {
    async changeConnect(value) {
      this.loading = true
      // 关闭
      if (!value) {
        this.feedback(this.$t('cmlpanel.remoteClose'))

        this.code = ''
        this.loading = false
        this.isOpen = false

        // 修改env状态
        // this.$store.commit('env/setIsConnectCapacityServer', false)
        this.$store.commit('remote/CLOSE')
        app.modal?.destroy({ componentsName: 'qr-image' })
        return
      }
      // 开启
      const { code } = this.$store.state.env.customer.info

      if (app.adminServer.ws?.readyState === 1) {
        // 说明已经连接了
        this.code = code
        this.loading = false
        this.isOpen = true
        this.$store.commit('remote/OPEN')

        this.feedback(this.$t('cmlpanel.remoteOpen'))
      } else {
        // 没有连接，去连接
        await this.connectToWSServer(code)

        this.feedback(this.$t('cmlpanel.remoteOpen'))
      }
      this.loading = false
    },
    async connectToWSServer(code) {
      if (app.adminServer.ws?.readyState === 1) {
        console.log('websocket 已经连接！')
        return
      }
      if (!code) {
        app.msg({
          type: 'error',
          content: this.$createElement(
            'span',
            null,
            `无法连接到ANOV服务器，请确保 code: ${code} 有效！`
          )
        })
        return
      }
      let serverPath = app.adminServer.serverPath
      let envState = false
      try {
        await connectWebsocket(serverPath, projectId, code)
        this.code = code
        this.failed = false
        // 修改env状态
        envState = true
        this.isOpen = true
        this.$store.commit('remote/OPEN')
      } catch (error) {
        console.warn(error)
        app.msg({
          type: 'error',
          content: this.$createElement('span', null, error)
        })
        this.code = ''
        this.failed = true
        // 修改env状态
        envState = false
        this.isOpen = false
        this.$store.commit('remote/CLOSE')
      }
      this.loading = false
      // 修改env状态
      this.$store.commit('env/setIsConnectCapacityServer', envState)
    },
    // 重新生成连接二维码
    regen() {
      const { code } = this.$store.state.env.customer.info
      /* app.adminServer.getConfig({ key: projectId, code }, (res) => {
        if (res && res.code === 0) {
          this.$store.commit('BIG_SCREEN_INFO', res.data)
        } else {
          this.failed = true
        }
      }) */
    },
    feedback(massage) {
      app.voiceFeedbackServer.speak(massage)
      app.msg({ type: 'info', content: massage })
    }
  }
}
</script>
<style lang="scss" scoped>
// @import '@/assets/css/sys-style/panel-var.scss';
// @import '@/assets/css/sys-style/panel-mixin.scss';
.qr-code {
  text-align: center;
}
</style>
